package com.lordjoe.collectiveintelligence;

import java.net.*;
import java.io.*;
import java.util.*;

/**
 * com.lordjoe.collectiveintelligence.GeoCodeUtilitiies
 *
 * @author Steve Lewis
 * @date May 24, 2009
 */
public class GeoCodeUtilitiies
{
    public static GeoCodeUtilitiies[] EMPTY_ARRAY = {};
    public static Class THIS_CLASS = GeoCodeUtilitiies.class;

    // key for www.lordjoe.com
    public static final String GOOGLE_KEY = "ABQIAAAAdlCxY_0qB0C6qq-kTw4sdxR1bGueBm2gR9zspaDtYCnkHbZt1RQZjIiCP2PDIQx7goRIByl9alTXlg";

    public static final String GEOCODE__REQUEST =
            "http://maps.google.com/maps/geo?q=%ADDRESS%&output=csv&oe=utf8&sensor=false&key=%GOOGLE_KEY%";

    /**
     * convert an address into a lat lon pair
     *
     * @param address valid address
     * @return possibly null LatLon
     */
    public static LatLon getLatLon(String address)
    {
        int retries = 0;
        String request = GEOCODE__REQUEST.replace("%GOOGLE_KEY%", GOOGLE_KEY);
        String ad = address.replace(" ", "%20");
        request = request.replace("%ADDRESS%", ad);
        String[] answer = null;
        // google seems to throttle this service
        try {
            Thread.sleep(1000);
        }
        catch (InterruptedException e1) { }
        while (retries < 3) {
            try {
                answer = readUrlLines(request);
                break;
            }
            catch (Exception e) {
                retries++;

            }
        }
        if(answer == null)
            return null;
        String line = answer[0];
        if (!line.startsWith("200,"))
            return null;
        String[] items = line.split(",");
        if (items.length != 4)
            return null;
        String ll = items[2] + "," + items[3];
        return new LatLon(ll);

    }

    /**
     * read a url and return the response (text) as an array  of
     * lines - this works fairly well for the csv response
     *
     * @param url - legal url returning text
     * @return array of strings for the url
     */
    public static String[] readUrlLines(String url)
    {
        try {
            URL u = new URL(url);
            URLConnection uc = u.openConnection();
            Object content = uc.getContent();
            if (content instanceof InputStream) {
                LineNumberReader inp = new LineNumberReader(
                        new InputStreamReader((InputStream) content));
                List<String> holder = new ArrayList<String>();
                String line = inp.readLine();
                while (line != null) {
                    holder.add(line);
                    line = inp.readLine();
                }
                String[] ret = new String[holder.size()];
                holder.toArray(ret);
                return ret;
            }
            throw new UnsupportedOperationException("Fix This"); // ToDo
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args)
    {
        String address = "4221 105th Ave NE, Kirkland WA";
        LatLon ll = getLatLon(address);
    }
}
